package com.rjkj.medicalwaste.ui.blue

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.rjkj.medicalwaste.adapter.BluetoothDeviceAdapter
import com.rjkj.medicalwaste.adapter.ItemClick
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.BleDeviceBean
import com.rjkj.medicalwaste.bean.BlueConnectResult
import com.rjkj.medicalwaste.databinding.FragmentBleListBinding
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel

class BleListFragment : BaseFragment<FragmentBleListBinding>() {
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()
    private var mBluetoothAdapter: BluetoothAdapter? = null
    private val listAdapter = BluetoothDeviceAdapter(object : ItemClick<BleDeviceBean> {
        override fun onClicked(view: View, value: BleDeviceBean) {
            Log.e(TAG, "onClicked: ${value.address}")
            connectToDevice(value)
        }
    })
    var deviceBlue = "-"
    val value = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            super.onScanResult(callbackType, result)
            Log.e(TAG, "onScanResult: ${result.toString()}")
            val device = result?.device
            if (device != null) {
                if (!deviceBlue.contains(device.address)) {
                    deviceBlue += device.address
                    if (device.name != null && device.name.contains("Furi")) {
                        listAdapter.addData(BleDeviceBean(
                            result.device?.name
                                ?: "NULL", result.device?.address ?: ""
                        ).also {
                            Log.e(TAG, "onDeviceFounded: ${it.toString()}")
                        })
                    }
                }
            }

        }

        override fun onBatchScanResults(results: MutableList<ScanResult>?) {
            super.onBatchScanResults(results)
        }

        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
        }
    }

    private fun connectToDevice(value: BleDeviceBean) {
        bluetoothControlViewModel.bluetoothTry.value = BlueConnectResult(value.address,99)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentBleListBinding.inflate(inflater, container, false)
        onSubscribeUi(binding)
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    override fun onSubscribeUi(binding: FragmentBleListBinding) {
//        val bluetoothManager = requireActivity().getSystemService("bluetooth") as BluetoothManager
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        binding.deviceList.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = listAdapter
        }
        val appCompatActivity = requireActivity() as AppCompatActivity
        appCompatActivity.setSupportActionBar(binding.toolbar)
        binding.toolbar.setNavigationOnClickListener {
            Log.e(TAG, "Navigation: ")
            findNavController().navigateUp()
        }
        binding.btScan.setOnClickListener {
            scanLeDevice(true)
        }
        setHasOptionsMenu(true)
    }


    fun scanLeDevice(enable: Boolean) {
        if (enable) {
            mBluetoothAdapter?.bluetoothLeScanner?.stopScan(value)
            mBluetoothAdapter?.bluetoothLeScanner?.startScan(value)
        } else {
            mBluetoothAdapter?.bluetoothLeScanner?.stopScan(value)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        scanLeDevice(false)
    }

    companion object {
        const val EXTRAS_DEVICE_NAME = "DEVICE_NAME"
        const val EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS"
        private const val REQUEST_ENABLE_BT = 1

    }
}